// 支持的语言列表
export const locales = ['en', 'zh'] as const;
export type Locale = (typeof locales)[number];

// 默认语言
export const defaultLocale: Locale = 'en';

// 导入语言文件
import zhMessages from '@/i18n/messages/zh.json';
import enMessages from '@/i18n/messages/en.json';

// 定义翻译消息类型
type TranslationMessages = {
  [key: string]: string | TranslationMessages
};

// 语言消息映射
const messages: Record<Locale, TranslationMessages> = {
  zh: zhMessages,
  en: enMessages
};

// 获取浏览器语言，优先从localStorage读取，其次从navigator.languages
export function getBrowserLanguage(): Locale {
  // 仅在客户端执行
  if (typeof window !== 'undefined') {
    // 首先尝试从localStorage获取
    const savedLocale = localStorage.getItem('locale');
    if (savedLocale && locales.includes(savedLocale as Locale)) {
      return savedLocale as Locale;
    }

    // 然后尝试从navigator.languages获取
    if (navigator.languages && navigator.languages.length) {
      for (const lang of navigator.languages) {
        const shortLang = lang.split('-')[0];
        if (locales.includes(shortLang as Locale)) {
          return shortLang as Locale;
        }
      }
    }
  }

  // 默认返回中文
  return 'en';
}

// 保存语言设置到localStorage
export function saveLocale(locale: Locale): void {
  if (typeof window !== 'undefined') {
    localStorage.setItem('locale', locale);
  }
}

// 获取翻译函数，用于在非React环境中使用
export async function getTranslations() {
  // 获取当前语言
  let locale: Locale = 'en'; // 默认使用中文

  if (typeof window !== 'undefined') {
    locale = getBrowserLanguage();
  }

  // 获取对应语言的消息
  const messageObj = messages[locale];

  // 返回翻译函数
  return function t(key: string, params?: Record<string, string>) {
    // 按照路径获取翻译值
    const keys = key.split('.');
    let value: TranslationMessages | string = messageObj;

    for (const k of keys) {
      if (value && typeof value === 'object' && k in value) {
        value = value[k];
      } else {
        return key; // 如果找不到翻译，返回键名
      }
    }

    // 如果找到的值不是字符串，返回键名
    if (typeof value !== 'string') {
      return key;
    }

    // 替换参数
    if (params) {
      return Object.entries(params).reduce(
        (acc, [paramKey, paramValue]) => acc.replace(`{${paramKey}}`, paramValue),
        value
      );
    }

    return value;
  };
}
